<!--
    @Title: LeaferEditor
    @Author  dudalei
    @Package 
    @Date  2024/10/14 09:37
    @description: 画布编辑组件
-->
<script setup lang="ts">
import { LeaferInjectKey } from '@/components/LeaferApp/LeaferInjectKeys'
import { EditorEvent } from 'leafer-editor'
import { PointerEvent } from 'leafer-ui'
import { createNode, type NodeTypes } from '@/components/LeaferApp/public'
import { useContextMenuFn, useShortcutKeys } from '@/components/LeaferApp/use/useContextMenu'

// 导入画布对象
const leaferApp = inject(LeaferInjectKey)

/**
 * 当前选择的长度
 */
// 是否选择了单个元素
const single = ref(false)
/**
 * 当前选择的元素类型
 */
const selectTag = ref('')

// 右键菜单
const showMenu = ref(false)
// 右键菜单配置
// 配置文档 https://docs.imengyu.top/vue3-context-menu-docs/api/ContextMenu.html
const optionsComponent = reactive({ x: 0, y: 0, theme: 'mac' })

/**
 * 获取画布对象
 */
const getApp = () => {
  return leaferApp!.value!
}
// 右键功能
const contextMenuFn = useContextMenuFn(getApp)

/**
 * 右键列表
 */
const contextMenuList = computed(() => {
  if (!leaferApp || !leaferApp.value) {
    return []
  }
  // 快捷建参考 https://vueuse.org/core/useKeyModifier/#usekeymodifier
  // const leafer = leaferApp.value

  return [
    {
      label: '全选 Control + A',
      show: true,
      click: contextMenuFn.Ctrl_A,
    },
    {
      label: '复制并粘贴 Control + C ',
      show: true,
      click: contextMenuFn.Ctrl_C,
    },
    /*    {
          label: '粘贴',
          show: true,
          click: () => {
            console.log('粘贴')
          }
        },*/
    {
      label: '删除 Delete',
      show: true,
      click: contextMenuFn.Delete,
    },
    {
      label: '成组 Control + G',
      show: !single.value,
      click: contextMenuFn.Ctrl_G,
    },
    {
      label: '解组 Control + U',
      show: selectTag.value === 'Group',
      click: contextMenuFn.Ctrl_U,
    },
    {
      label: '向上移动一层 [',
      show: true,
      click: contextMenuFn.upOne,
    },
    {
      label: '向下移动一层 ]',
      show: true,
      click: contextMenuFn.downOne,
    },
    {
      label: '置顶 Control + D',
      show: true,
      click: contextMenuFn.Ctrl_D,
    },
    {
      label: '置底 Control + B',
      show: true,
      click: contextMenuFn.Ctrl_B,
    },
    // 多选时才显示
    {
      label: '垂直居中',
      show: !single.value,
      click: contextMenuFn.verticallyCentered,
    },
    // 多选时才显示
    {
      label: '水平居中',
      show: !single.value,
      click: contextMenuFn.horizontallyCentered,
    },
  ]
})

/**
 * 拖动事件
 * @param e
 */
const dragover = (e: DragEvent) => {
  e.preventDefault()
}
/**
 * 结束拖拽
 * @param e
 */
const drop = (e: DragEvent) => {
  if (!leaferApp || !leaferApp.value || !e.dataTransfer) {
    return
  }

  const type = e.dataTransfer.getData('text/plain') as NodeTypes

  if (!type) {
    return
  }
  /**
   * 获取在应用中的 page 坐标（传入一个浏览器窗口的 client 坐标 转换），update 表示是否强制更新画布的 clientBounds（一般会自动更新）。
   *
   * 可用于转换浏览器原生事件坐标（自带 clientX / clientY 坐标属性）到应用中。
   */
  const toPoint = leaferApp.value.getPagePointByClient({ clientX: e.clientX, clientY: e.clientY })

  console.log('结束拖拽', toPoint)
  if (!createNode[type]) {
    return
  }
  const node = createNode[type]!(toPoint)

  leaferApp.value.tree.add(node)
}
defineExpose({ dragover, drop })

/**
 * 右键菜单
 * @param e
 */
const menuTapEvent = (e: EditorEvent) => {
  console.log('右键')
  if (!leaferApp || !leaferApp.value) {
    return
  }
  const leafer = leaferApp.value

  const list = leafer.editor.list
  single.value = leafer.editor.single
  selectTag.value = e.target.tag

  if (list.length === 0) {
    showMenu.value = false
    return
  }

  showMenu.value = true
  optionsComponent.x = e.origin.x
  optionsComponent.y = e.origin.y
}

const initEditor = (): void => {
  if (!leaferApp || !leaferApp.value) {
    return
  }
  console.log('编辑器初始化')
  const leafer = leaferApp.value
  // 使用快捷键
  useShortcutKeys(leafer, contextMenuFn)
  /**
   * 监听选择事件
   */
  /*  leafer.editor.on(EditorEvent.SELECT, (e: EditorEvent) => {
    console.log('选择元素触发了')
  })*/

  /**
   * 监听点击事件
   */
  /*  leafer.editor.on(PointerEvent.CLICK, (e: EditorEvent) => {
    console.log('点击事件', e.target)
  })*/

  /**
   * 监听右键事件
   */
  leafer.editor.on(PointerEvent.MENU_TAP, menuTapEvent)
}

watchEffect(() => {
  if (leaferApp && leaferApp.value) {
    initEditor()
  }
})
</script>

<template>
  <div v-show="false">
    <!--    右键菜单 -->
    <context-menu v-model:show="showMenu" :options="optionsComponent">
      <template v-for="item in contextMenuList" :key="item.label">
        <context-menu-item v-show="item.show" :label="item.label" @click="item.click" />
        <context-menu-sperator v-show="item.show" /><!--use this to add sperator-->
      </template>
      <!--      <context-menu-group label="Menu with child">
              <context-menu-item label="Item1" @click="onMenuClick(2)" />
              <context-menu-item label="Item2" @click="onMenuClick(3)" />
              <context-menu-group label="Child with v-for 50">
                <context-menu-item v-for="index of 10" :key="index" :label="'Item3-'+index" @click="onLoopMenuClick(index)" />
              </context-menu-group>
            </context-menu-group>-->
    </context-menu>
  </div>
</template>

<style scoped lang="scss"></style>
